package com.ecnucs.shortlink.utils;

import com.ecnucs.shortlink.common.ShortLinkException;
import okhttp3.*;

import java.io.IOException;

public class HttpUtil {
    private static final OkHttpClient httpClient = new OkHttpClient();

    public static String getData(String url) throws ShortLinkException {
        // 创建请求
        Request request = new Request.Builder()
                .url(url)
                .build();

        // 发送请求并获取响应
        try (Response response = httpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new RuntimeException("请求失败: " + response.code());
            }
            return response.body().string(); // 获取响应体
        } catch (IOException e) {
            throw new ShortLinkException();
        }
    }

    public static String getData(String url, String token) throws ShortLinkException {
        // 创建请求
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", token)
                .build();

        // 发送请求并获取响应
        try (Response response = httpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new RuntimeException("请求失败: " + response.code());
            }
            return response.body().string(); // 获取响应体
        } catch (IOException e) {
            throw new ShortLinkException();
        }
    }

    public static String postData(String url, String json) throws ShortLinkException {
        // 定义请求体
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(json, JSON);

        // 创建请求
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        // 发送请求并获取响应
        try (Response response = httpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new RuntimeException("请求失败: " + response.code());
            }
            return response.body().string();
        } catch (IOException e) {
            throw new ShortLinkException();
        }
    }

    public static String postData(String url, String json, String token) throws ShortLinkException {
        // 定义请求体
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(json, JSON);

        // 创建请求
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .addHeader("Authorization", token)
                .build();

        // 发送请求并获取响应
        try (Response response = httpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new RuntimeException("请求失败: " + response.code());
            }
            return response.body().string();
        } catch (IOException e) {
            throw new ShortLinkException();
        }
    }
}
